package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.advice.LogOperation;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Override
    public PageResult<Clazz> clazzSelect(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.clazzSelect(clazzQueryParam);
//        clazzList.forEach(s -> {
//            if (s.getBeginDate().isAfter(LocalDate.now())){
//                s.setStatus("未开课");
//            }else if (s.getEndDate().isBefore(LocalDate.now())) {
//                s.setStatus("已结课");
//            }else {
//                s.setStatus("在读中");
//            }
//        });
        Page p = (Page) clazzList;
        PageResult<Clazz> pageResult = new PageResult<>();
        pageResult.setRows(p.getResult());
        pageResult.setTotal(p.getTotal());
        return pageResult;
    }

    @LogOperation
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result clazzDelete(Integer id) {
        List<Student> studentList = studentMapper.studentGetByClazzId(id);
        if (studentList.isEmpty()){
            clazzMapper.clazzDelete(id);
            return Result.success();
        }else {
            return Result.error("该班级下有人,无法删除");
        }
    }

    @Override
    @LogOperation
    public void clazzInsert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.clazzInsert(clazz);
    }

    @Override
    public Clazz clazzGetById(Integer id) {
        Clazz clazz = clazzMapper.clazzGetById(id);
        return clazz;
    }

    @Override
    @LogOperation
    public void clazzUpdate(Clazz clazz) {
        clazzMapper.clazzUpdate(clazz);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }
}
